<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './websiteBannerTableData';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { websiteBannerSaveApi,websiteBannerUpdateApi } from '/@/api/website/websiteBannerApi';

export default defineComponent({
  name: 'WebsiteBannerDrawer.vueDrawer',
  components: { BasicDrawer, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);

    const bannerId = ref('');

    const [registerForm, { resetFields, setFieldsValue , validate }] = useForm({
      labelWidth: 150,
      schemas: formSchema,

      showActionButtonGroup: false,
      baseColProps: { lg: 24, md: 24 },
    });

    const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
      resetFields();
      setDrawerProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      bannerId.value = data?.data?.bannerId;

      if (unref(isUpdate)) {
        if(data.data.bannerImg){
          data.data.bannerImg = [ data.data.bannerImg ];
        }
        setFieldsValue({
          ...data.data,
        });

      }
      /*updateSchema({
        field: 'parentMenu',
        componentProps: {  },
      });*/
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    async function handleSubmit() {
      try {
        const values = await validate();
        values.bannerId = bannerId.value;
        setDrawerProps({ confirmLoading: true });
        // TODO custom api
        if(values.bannerImg)
          values.bannerImg = values.bannerImg[0];
        console.log(values);
        await (!unref(isUpdate) ? websiteBannerSaveApi(values) : websiteBannerUpdateApi(values));
        closeDrawer();
        emit('success');
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }

    return { registerDrawer, registerForm, getTitle, handleSubmit };
  },
});
</script>
